from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from .base_model import BaseModel

class OperationLog(BaseModel):
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    OPERATION_CHOICES = (
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('view', '查看'),
        ('login', '登录'),
        ('logout', '登出'),
    )
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='operation_logs', verbose_name='用户')
    operation_type = models.CharField(max_length=20, choices=OPERATION_CHOICES, verbose_name='操作类型')
    content_type = models.CharField(max_length=50, verbose_name='对象类型')
    object_id = models.IntegerField(verbose_name='对象ID')
    object_name = models.CharField(max_length=100, verbose_name='对象名称')
    timestamp = models.DateTimeField(default=timezone.now, verbose_name='操作时间')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    details = models.TextField(blank=True, null=True, verbose_name='操作详情')
    
    class Meta:
        verbose_name = '操作日志'
        verbose_name_plural = '操作日志'
        ordering = ['-timestamp']
    
    def __str__(self):
        return f"{self.user.username} {self.get_operation_type_display()} {self.content_type}: {self.object_name}"